/**
 * @name v-input 输入框限制
 * @example: <a-input v-input:float /> 浮点数 两位小数
 * @example: <a-input v-input:int /> 整型数 0,1,2,3...
 * @example: <a-input v-input:age /> 年龄 0-150
 * @example: <a-input v-input:idcard /> 身分证
 * @example: <a-input v-input:float.3 />浮点数 三位小数
 */
import { nextTick } from 'vue'

export default {
  mounted(el, binding) {
    const input = el.tagName === 'INPUT' ? el : el.querySelector('input')
    el.addEventListener('input', () => {
      let inputValue = input?.value
      if (binding.arg === 'float') {
        const decimal = Object.keys(binding.modifiers)[0] || 2
        const regex = new RegExp(`^\\d+(\\.\\d{0,${decimal}})?$`)
        if (!regex.test(inputValue)) {
          inputValue = inputValue.replace(/[^\d.]/g, '')
          const decimalIndex = inputValue.indexOf('.')
          if (decimalIndex !== -1) {
            inputValue = inputValue.substring(0, decimalIndex + Number(decimal) + 1)
          }
        }
      } else if (binding.arg === 'int') {
        inputValue = inputValue.replace(/[^\d]/g, '')
      } else if (binding.arg === 'idcard') {
        inputValue = inputValue.replace(/[^\dX]/g, '')
        if (inputValue.length > 18) {
          inputValue = inputValue.slice(0, 18)
        }
      } else if (binding.arg === 'age') {
        inputValue = inputValue.replace(/[^\d]/g, '')
        inputValue = inputValue ? Number(inputValue).toString() : inputValue //去掉开头多个0
        if (inputValue > 150) {
          inputValue = 150
        }
      }
      nextTick(() => {
        input.value = inputValue
      })
    })
  }
}
